<?php
namespace admin\Controller;
use Admin\Controller\BaseController;

/**
 * 
 */
class CategoryController extends BaseController
{
	//分类列表
	public function lists()
	{
		$keyword = I('keyword','','trim');      //过滤开头结尾空格
		if($keyword){
            $map['category'] = array('like',"%$keyword%");//模糊查询
            $this->assign('keyword',$keyword);  //输出数据
        }
        $category = M('category');
        $count  = $category->count();         //category表总数据量
        $row    = 10;                           //每页显示条数
        $Page   = new \Think\Page($count,$row); //实例化分页类
        $show   = $Page->show();                //调用show方法
        $datalists = $category->where($map)->order('sort desc')
            ->limit($Page->firstRow.','.$Page->listRows) //结合limit方法
            ->select();
        $this->assign('page',$show);    //输出分页数据
        $title  = '分类列表管理';
        $this->assign('title',$title);
        $this->assign('datalists',$datalists);
        $this->display();
    }
    //添加分类
    public function add(){
    	if(IS_POST){
    		$data = I('post.');
    		$category = M('category');
    		$map['id'] = $data['id'];
            if($data['id']){    //编辑
            	$res  = $category->where($map)->save($data);
            }else{              //新增
            	$res  = $category->add($data);
            }
            if($res !== false){
                $this->success('操作成功',U('lists'));  //跳转到列表页
            }else{
            	$this->error('添加失败');
            }
        }else{
        	/**id存在是编辑的情况，需要获取分类名称**/
        	$map['id']  = $id = I('get.id');
        	if($id){
        		$category = M('category');
                $category = $category->where($map)->select(); //查找分类名称
                $this->assign('get_id',$id);
                $this->assign('data',$category);
            }
            $this->display();
        }
    }

    /**
     * 单选删除
     */
    public function delete(){
    	$map['id'] = I('id',0,'int');
    	$res = M('category')->where($map)->delete();
    	if($res){
    		$message = '删除成功';
    	}else{
    		$message = '删除失败';
    	}
    	$this->ajaxReturn($message);
    }

    /**
     * 全选删除
     */
    public function delAll(){
    	$ids = I('ids',0);
        //删除所有选中高级分类
    	$map['id']  = array('in',$ids);
    	if(M('category')->where($map)->delete()){
    		$message = '删除成功';
    	}else {
    		$message = '删除失败';
    	}
    	$this->ajaxReturn($message);
    }


}